package picturetaker.application;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import picturetaker.utility.ApplicationConstants;
import picturetaker.utility.MyXMLReader;

import picturetaker.domain.Camera;
import picturetaker.domain.Picture;

public class MainThread implements Runnable, ApplicationConstants {

	private boolean running = true;

	private long sleepingTime = 0;

	private List<Camera> cameras = null;

	private List<CameraThread> myThreads = null;

	private BlockingQueue<Picture> queueToIO = null;
	
	private BlockingQueue<Picture> queueToDB = null;

	private final Object lock = new Object();

	public MainThread(List<Camera> cameras) {
		this.queueToIO = new ArrayBlockingQueue<Picture>(CAPACITY);
		this.queueToDB = new ArrayBlockingQueue<Picture>(CAPACITY);
		this.sleepingTime = MyXMLReader.readTimerConfiguration();
		this.myThreads = new ArrayList<CameraThread>();
		if (sleepingTime == ERROR_RETURN)
			sleepingTime = DEFAULT_TIMER;
		this.cameras = cameras;
		new Thread(new PersistenceThread(queueToDB)).start();
		new Thread(new FileIOThread(queueToIO,queueToDB)).start();
		this.initCameraThreads();
	}

	private void initCameraThreads() {
		Iterator<Camera> iter = cameras.iterator();
		Camera cam = null;
		CameraThread currentCamThread = null;
		while (iter.hasNext()) {
			cam = iter.next();
			currentCamThread = new CameraThread(cam, queueToIO, lock);
			myThreads.add(currentCamThread);
			new Thread(currentCamThread).start();
		}

	}

	public void run() {
		if (running) {
			try {
				synchronized (lock) {
					this.lock.notifyAll();
				}
				Thread.sleep(sleepingTime);
				while(!this.queueToDB.isEmpty()){
					wait(1000);					
				}
			} catch (InterruptedException e) {
				// Ignore
			}
		}
	}

	private void reinitCameraThreads() throws MalformedURLException {
		Iterator<CameraThread> iter = this.myThreads.iterator();
		while (iter.hasNext()) {
			iter.next().setRunning(false);
		}
		this.myThreads.clear();
		this.cameras = AppCore.initCameras();
		this.sleepingTime = MyXMLReader.readTimerConfiguration();
		if (sleepingTime == ERROR_RETURN)
			sleepingTime = DEFAULT_TIMER;
		initCameraThreads();
	}
}
